package com.yanqu.road.server.manager.tradewar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eTradeWarBattleType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.tradewar.*;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.TradeWarPb;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.cross.tradewar.CrossTradeWarProto;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.pb.tradewar.TradeWarProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.config.GoodsMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossTradeWarMgr extends TempMgr {
    //活动id 大分组
    private static Map<Integer,CrossTradeWarActivityGroup> crossTradeWarActivityMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (CrossTradeWarActivityGroup crossTradeWarActivityGroup: crossTradeWarActivityMap.values()){
            for (CrossTradeWarActivity crossTradeWarActivity : crossTradeWarActivityGroup.getGroupMap().values()){
                crossTradeWarActivity.save();
            }
        }
        return true;
    }

    @Override
    public boolean reloadData() {
        Map<Integer, ActivityInfo> openActivityMap = CrossTradeWarActivityMgr.getOpenActivityMap();
        //拿出当前跨服id
        long serverId = CrossBaseServer.getInstance().getServerId();
        for (Map.Entry<Integer, ActivityInfo> activityInfoEntry : openActivityMap.entrySet()) {
            if (!crossTradeWarActivityMap.containsKey(activityInfoEntry.getKey())) {
                Map<Integer, UnionActivityGroup> groupMap = Cross2UnionActivityGroupMgr.getGroupMap(activityInfoEntry.getKey());
                if (groupMap != null) {
                    for (UnionActivityGroup unionActivityGroup : groupMap.values()) {
                        if (unionActivityGroup.getCrossServerId() == serverId) {
                            getActivity(activityInfoEntry.getKey(), unionActivityGroup.getGroupId());
                        }
                    }
                }
            }
        }
        return true;
    }

    public static synchronized CrossTradeWarActivity getActivity(int activityId, int groupId){
        UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
        if (groupData == null) {
            return null;
        }
        if (crossTradeWarActivityMap.get(activityId)== null){
            ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
            if (activityInfo == null) {
                return null;
            }
            CrossTradeWarActivityGroup activityGroup = new CrossTradeWarActivityGroup(activityInfo);
            crossTradeWarActivityMap.put(activityId,activityGroup);
        }
        // 拿分组数据
        CrossTradeWarActivityGroup group = crossTradeWarActivityMap.get(activityId);
        return group.getActivity(activityId,groupId);
    }

    public static void resetOneDay() {
        for (CrossTradeWarActivityGroup value : crossTradeWarActivityMap.values()){
            Map<Integer, CrossTradeWarActivity> groupMap = value.getGroupMap();
            for (CrossTradeWarActivity activity:groupMap.values()){
                activity.resetOneDay();
            }
        }
    }



    /**
     * 获取游戏服公告信息
     */
    public static void getServerNoticeList(int activityId, long serverId){
        ActivityInfo activityInfo = CrossTradeWarActivityMgr.getActivityInfoIfNotLoadDb(activityId);
        if (activityInfo == null){
            return;
        }
        CrossTradeWarActivityGroup crossTradeWarActivityGroup = crossTradeWarActivityMap.get(activityId);
        Map<Integer, CrossTradeWarActivity> groupMap = crossTradeWarActivityGroup.getGroupMap();
        if (groupMap!=null){
            for (CrossTradeWarActivity activity: groupMap.values()){
                CrossTradeWarProto.CrossTradeWarNoticeListMsg.Builder listMsg = activity.getNoticeListMsg();
                CrossTradeWarProto.CrossTradeWarNoticeListSyncMsg.Builder syncMsg = CrossTradeWarProto.CrossTradeWarNoticeListSyncMsg.newBuilder();
                syncMsg.setGroupId(activity.getGroupId());
                syncMsg.setActivityId(activityId);
                syncMsg.setDataList(listMsg);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_TRADE_WAR_NOTICE_LIST_SYNC, syncMsg);
                MessageHelper.sendPacket(serverId, 0, pbMsg);
            }
        }
    }



    /**
     * 获取通缉详单
     * @param activityId
     * @param wantedUid
     * @param userId
     * @param serverId
     * @return
     */
    public static CrossTradeWarProto.CrossTradeWarWantedDetailRespMsg.Builder getTradeWarWantedDetailRespMsg(int activityId, String wantedUid, long userId, long serverId) {
        CrossTradeWarProto.CrossTradeWarWantedDetailRespMsg.Builder respMsg = CrossTradeWarProto.CrossTradeWarWantedDetailRespMsg.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            respMsg.setRet(GameErrorCode.E_TRADE_WAR_WANTED_NO_EXIST);
            return respMsg;
        }
        CrossTradeWarActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            getLogger().error("跨服商战活动 活动id{}分组{} 不存在",activity,groupId);
            respMsg.setRet(GameErrorCode.E_TRADE_WAR_WANTED_NO_EXIST);
            return respMsg;
        }
        TradeWarWanted tradeWarWanted = activity.getTradeWarWanted(wantedUid);
        if(null == tradeWarWanted){
            tradeWarWanted = activity.getFinishWanted(activityId, wantedUid);
            if(null == tradeWarWanted) {
                respMsg.setRet(GameErrorCode.E_TRADE_WAR_WANTED_NO_EXIST);
                return respMsg;
            }
        }
        TradeWarProto.TradeWarWantedTempMsg.Builder wantedMsg = TradeWarPb.parseTradeWarWantedTempMsg(tradeWarWanted);
        if(null != wantedMsg){
            wantedMsg.setTrackTimes(activity.getUserTraceTimes(wantedUid, userId, serverId));
            respMsg.setWantedInfo(wantedMsg);
        }
        List<TradeWarTrackRecord> recordList = activity.getTradeWarTrackRecordList(wantedUid);
        if(null != recordList) {
            for (TradeWarTrackRecord trackRecord : recordList) {
                TradeWarProto.TradeWarTrackRecordTempMsg.Builder msg = TradeWarPb.parseTradeWarTrackRecordTempMsg(trackRecord);
                if(null != msg){
                    respMsg.addTrackRecordList(msg);
                }
            }
        }
        respMsg.setRet(0);
        return respMsg;
    }

    /**
     * 判断能进行追缉
     * @param activityId
     * @param wantedUid
     * @param userId
     * @param serverId
     * @return
     */
    public static int canCrossTrack(int activityId, String wantedUid, long userId, long serverId, boolean calcTrackTimes,
                                    int dailyTrackTimes, int limitTrackTimes, String myUnionId){
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            return GameErrorCode.E_UNION_ACTIVITY_GROUP_NO_ABLE;
        }
        CrossTradeWarActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            getLogger().error("跨服商战活动 活动id{}分组{} 不存在",activity,groupId);
            return GameErrorCode.E_TRADE_WAR_WANTED_NO_EXIST;
        }

        TradeWarWanted tradeWarWanted = activity.getTradeWarWanted(wantedUid);
        if(null == tradeWarWanted){
            return GameErrorCode.E_TRADE_WAR_WANTED_NO_EXIST;
        }
        if(!isWantedTime(tradeWarWanted)){
            return GameErrorCode.E_TRADE_WAR_WANTED_OVER_TIME;
        }
        long publishUserId = tradeWarWanted.getUserId();
        if(calcTrackTimes) {
            if (userId != publishUserId) {//不是自己发布的，判断一下次数是否够用
                int useItemId = tradeWarWanted.getUseItemId();
                GoodsInfo goodsInfo = GoodsMgr.getGoodsInfo(useItemId);
                int addTimes = 1;
                if (null != goodsInfo) {
                    addTimes = goodsInfo.getParamList().get(0).intValue();
                }
                if (dailyTrackTimes + addTimes > limitTrackTimes) {
                    return GameErrorCode.E_TRADE_WAR_TRACK_TIMES_OVER;
                }
            }
        }
        // 换掉 判断有多少人打过了 旧的是匹配次数 新版换成已被打的次数
        if (userId != publishUserId) {
            if (activity.isHelpUserTrackFull(wantedUid, publishUserId)) {
                return GameErrorCode.E_TRADE_WAR_WANTED_OVER_BATTLE_TIMES;
            }
        } else {
            if (activity.isPublishUserTrackFull(wantedUid, publishUserId)) {
                return GameErrorCode.E_TRADE_WAR_WANTED_OVER_BATTLE_TIMES;
            }
        }

        if(activity.getUserTraceTimes(wantedUid, userId, serverId) >= GameConfig.TRADE_WAR_WANTED_USER_BATTLE_TIMES){
            return GameErrorCode.E_TRADE_WAR_WANTED_TRACK_TIMES_OVER;
        }
        // 判断下发布者是否同商会
        UserBaseInfo publishUserBaseInfo = CrossUserMgr.getUserBaseInfo(publishUserId);
        if (publishUserBaseInfo != null) {
            // 发布者商会信息
            String unionUid = publishUserBaseInfo.getUnionUid();
            if (StringUtils.isNullOrEmpty(unionUid) || unionUid.equals("0") || !unionUid.equals(myUnionId)) {
                // 判断下时间间隔
                if (System.currentTimeMillis() / 1000 - tradeWarWanted.getWantedTime() < GameConfig.TRADE_WAR_WANTED_LIMIT_TIME) {
                    return GameErrorCode.E_TRADE_WAR_TRACK_TOO_FAST_NO_SAME_UNION;
                }
            }
        }
        return 0;
    }

    /**
     * 追缉
     * @param activityId
     * @param wantedUid
     * @param userId
     * @param serverId
     * @return
     */
    public static int crossTrack(int activityId, String wantedUid, long userId, long serverId, String unionId){
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            return GameErrorCode.E_UNION_ACTIVITY_GROUP_NO_ABLE;    //不配
        }
        CrossTradeWarActivity activity = getActivity(activityId,groupId);
        if (activity == null){
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_FOUND_BATTLE_FAIL;
        }
        return activity.crossTrack(activityId,wantedUid,userId,serverId,unionId);
    }

    /**
     * 获取通缉map
     * @param activityId
     * @return
     */
    private static Map<String, TradeWarWanted> getTradeWarWantedMap(int activityId,int groupId){
        CrossTradeWarActivity activity = getActivity(activityId, groupId);
        if (activity != null){
            return new ConcurrentHashMap<>(activity.getTradeWarWantedMap());
        }
        return null;
    }

    /**
     * 获取通缉
     * @param activityId
     * @param wantedUid
     * @return
     */
    public static TradeWarWanted getTradeWarWanted(int activityId, String wantedUid,int groupId){
        Map<String, TradeWarWanted> dataMap = getTradeWarWantedMap(activityId,groupId);
        if(null != dataMap){
            return dataMap.get(wantedUid);
        }
        return null;
    }


    /**
     * 是否在通缉时间内
     * @param wanted
     * @return
     */
    public static boolean isWantedTime(TradeWarWanted wanted){
        if(null == wanted){
            return false;
        }
        long nowTime = System.currentTimeMillis() / 1000;
        return nowTime < wanted.getWantedTime() + GameConfig.TRADE_WAR_WANTED_TIME;
    }



    public static void wantedOverTimeTask() {
        for (CrossTradeWarActivityGroup group:crossTradeWarActivityMap.values()){
            Map<Integer, CrossTradeWarActivity> groupMap = group.getGroupMap();
            for (CrossTradeWarActivity activity:groupMap.values()){
                activity.wantedOverTimeTask();
            }
        }
    }

    /**
     * 是否跨服追缉变更
     * @param trackChangeType
     * @return
     */
    public static boolean isCrossTrackChange(int trackChangeType){
        return trackChangeType == eTradeWarBattleType.Challenge.getValue();
    }

    /**
     * 获取跨服简略公告
     * @param activityId
     * @param userId
     * @param serverId
     * @param enemyUserId
     * @param enemyServerId
     * @return
     */
    public static List<CrossTradeWarSimpleNotice> getCrossTradeWarSimpleNoticeList(int activityId, long userId, long serverId, long enemyUserId, long enemyServerId){

        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            return null;    //不配
        }
        CrossTradeWarActivity activity = getActivity(activityId,groupId);
        if (activity == null){
            return null;
        }
        return activity.getCrossTradeWarSimpleNoticeList(userId, serverId, enemyUserId, enemyServerId);
    }

    /**
     * 获取商战通缉榜榜首
     * @param activityId
     * @return
     */
    public static RankProto.RankTempMsg.Builder getTradeWarWantedRankTop(int activityId,int groupId){
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            return null;    //不配
        }
        CrossTradeWarActivity activity = getActivity(activityId,groupId);
        if (activity == null){
            return null;
        }
        if(null != activity.getTradeWarWantedRankTop()){
            return activity.getTradeWarWantedRankTop();
        }else {
            return null;
        }
    }


    /**
     * 获取商战通缉榜
     * @param activityId
     * @return
     */
    public static RankProto.RankListMsg.Builder getTradeWarWantedRankMsg(int activityId,int groupId){
        CrossTradeWarActivity activity = getActivity(activityId, groupId);
        if (activity != null){
            return activity.getTradeWarWantedRankMsg();
        }
        return null;
    }



}
